package com.molichuxing.gateway.bff.car.services.Impl;

import com.molichuxing.framework.dto.Paged;
import com.molichuxing.framework.exception.BizException;
import com.molichuxing.framework.result.ResponseCodeEnum;
import com.molichuxing.framework.result.ResponseResult;
import com.molichuxing.framework.utils.DateUtil;
import com.molichuxing.framework.utils.ObjectCastUtil;
import com.molichuxing.gateway.bff.basic.entity.response.VehicleModlemakeVo;
import com.molichuxing.gateway.bff.car.convertor.Convert;
import com.molichuxing.gateway.bff.car.entity.response.CarDetailVo;
import com.molichuxing.gateway.bff.car.entity.response.CarVo;
import com.molichuxing.gateway.bff.car.entity.response.IovTrajectoryVo;
import com.molichuxing.gateway.bff.car.services.CarBffService;
import com.molichuxing.gateway.property.PowerTypeEnum;
import com.molichuxing.gateway.utils.RequestAttrUtil;
import com.molichuxing.services.business.dto.response.*;
import com.molichuxing.services.business.service.*;
import com.molichuxing.services.infrastructure.dto.response.*;
import com.molichuxing.services.infrastructure.dto.response.CarDto;
import com.molichuxing.services.infrastructure.service.*;
import com.molichuxing.services.property.StockCarStockTypeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Author: renzhengyu
 * @Description:
 * @Date: Created in 14:53 2019/9/11
 * @Modified By:
 **/
@Service("carBffService")
public class CarBffServiceImpl implements CarBffService {

    private static final Logger logger = LoggerFactory.getLogger(CarBffServiceImpl.class);

    @Resource
    private CarBizService carBizService;

    @Resource
    private CarService carService;

    @Resource
    private VehicleBizService vehicleBizService;

    @Resource
    private VehicleService vehicleService;

    @Resource
    private StockCarBizService stockCarBizService;

    @Resource
    private StoreBizService storeBizService;

    @Resource
    private StoreService storeService;

    @Resource
    private VehicleColorService vehicleColorService;

    @Resource
    private StockStoreService stockStoreService;

    @Resource
    private CarLicencePlateBizService carLicencePlateBizService;

    @Resource
    private VehiclePictureService vehiclePictureService;

    @Resource
    private OrderDealerDeliveryService orderDealerDeliveryService;

    @Resource
    private IovCarService iovCarService;

    @Resource
    private StockRecordBizService stockRecordBizService;

    @Resource
    private StockCarService stockCarService;


    @Override
    public Paged<CarVo> getCarList(Map<String, Object> selectParams, Integer pageNum, Integer pageSize) throws Exception {
        Integer stockId = ObjectCastUtil.castInteger(selectParams.get("stockId"));
        if(null == stockId) {
            //获取当前登录的经销商id
            Integer dealerId = RequestAttrUtil.getCurrentDealerId();
            List<Integer> storeIds = storeService.getAllStoreIdByDealer(dealerId);
            if((null != storeIds)&&(storeIds.size() > 0)) {
                List<Integer> stockIds = stockStoreService.getStockIds(storeIds);
                if((null != stockIds)&&(stockIds.size() > 0)) {
                    selectParams.put("stockIds", stockIds);
                }else {
                    selectParams.put("stockId", 0);
                }
            }else {
                selectParams.put("stockId", 0);
            }
        }
        selectParams.put("businessTypeList", Arrays.asList(0,1,2));
        Paged<CarDto> carDtoList = carService.getCarDealerPage(selectParams,pageNum, pageSize);
        Paged<CarVo> page = Convert.toCarVoPage(carDtoList, getVehicleName(carDtoList.getList()), getVehicleColor(carDtoList.getList()));
        getVehicleStock(page.getList());
        return page;
    }

    @Override
    public CarDetailVo getCarDetail(Integer carId)throws Exception {
        CarDetailBizDto carDetailBizDto = carBizService.getCarDetail(carId);
        if(null == carDetailBizDto) {
            return null;
        }
        CarDetailVo carDetailVo = Convert.toCarDetailVo(carDetailBizDto);
        CarLicencePlateDetailDto licencePlate = carLicencePlateBizService.getLicencePlate(carId);
        if(null == licencePlate) {
            return null;
        }
        carDetailVo.setRegisterCard(licencePlate.getRegisterCard());
        carDetailVo.setDrivingLicense(licencePlate.getDrivingLicense());
        carDetailVo.setTaxProof(licencePlate.getTaxProof());
        if(null != carDetailVo) {
            Map<Integer, VehicleNameBizDto>  vehicleMap = vehicleBizService.getCarByModelNameList(Arrays.asList(carDetailVo.getVehicleId()));
            if(vehicleMap != null&&(null != vehicleMap.get(carDetailVo.getVehicleId()))) {
                VehicleNameBizDto vehicleNameBizDto = vehicleMap.get(carDetailVo.getVehicleId());
                carDetailVo.setVehicleName(vehicleNameBizDto.getModelName());
                carDetailVo.setVehicleMake(vehicleNameBizDto.getSubBrandName());
                carDetailVo.setVehicleModel(vehicleNameBizDto.getSeriesName());
            }
            VehicleColorDto vehicleColorDto = vehicleColorService.getVehicleColorByvehicleColorId(carDetailVo.getVehicleColorId());
            if(vehicleColorDto != null) {
                carDetailVo.setVehicleColorName(vehicleColorDto.getName());
            }
            VehicleDto vehicleDto = vehicleService.getVehicleByVehicleId(carDetailVo.getVehicleId());
            if(null != vehicleDto && null != vehicleDto.getPowerType()) {
                carDetailVo.setPowerTypeStr(PowerTypeEnum.getName(vehicleDto.getPowerType()));
            }
            List<VehiclePictureDto> vehiclePictureList = vehiclePictureService.getVehiclePictureByVehicleId(carDetailVo.getVehicleId());
            if((null != vehiclePictureList)&&(vehiclePictureList.size() > 0)) {
                for(VehiclePictureDto vehiclePictureDto : vehiclePictureList) {
                    if(vehiclePictureDto.getIsWhiteBg() && 1 == vehiclePictureDto.getPicDetailType()) {
                        carDetailVo.setVehicleImg(vehiclePictureDto.getServerUrl());
                        break;
                    }
                }
            }
            StockCarBizDto stockCarBizDto = stockCarBizService.getStockCar(carDetailVo.getCarId());
            if(null != stockCarBizDto && null != stockCarBizDto.getStoreId()) {
                try {
                    StoreDto storeDto = storeService.getStoreById(stockCarBizDto.getStoreId());
                    if(null != storeDto) {
                        carDetailVo.setCurrentStore(storeDto.getShortName());
                    }
                }catch (Exception e) {
                    logger.error("查询门店信息异常");
                }
            }
            Integer startMileage = orderDealerDeliveryService.getTotalMileageByCarId(carId);
            if(null != startMileage) {
                carDetailVo.setInitialMileage(startMileage+"");
            }
            ResponseResult<Map<String, IovMileageDto>> iovMap = iovCarService.getMileageByVins(Arrays.asList(carDetailVo.getVin()));
            if((null != iovMap)&&(ResponseCodeEnum.SUCCESS.getCode().equals(iovMap.getCode()))) {
                IovMileageDto iovMileageDto = iovMap.getData().get(carDetailVo.getVin());
                if(null != iovMileageDto) {
                    carDetailVo.setDrivingName(iovMileageDto.getOdo()+"");
                }
            }
        }
        return carDetailVo;
    }


    @Override
    public ResponseResult<List<String>> getTrajectoryTime(String vin) {
        //获取当前登录的经销商id
        CarDto carDto = carService.getCarByVin(vin);
        if(null == carDto) {
            return null;
        }
        StockCarDto resultStock = stockCarService.getStorageTime(carDto.getId());
        if(null == resultStock) {
            return null;
        }

        ResponseResult<List<String>> dateTimeResult = iovCarService.getTrajectoryTime(vin);
        List<String> result = null;
        if(dateTimeResult.getCode().equals(ResponseCodeEnum.SUCCESS.getCode())) {
            List<String> dateTimeList = dateTimeResult.getData();
            if((null != dateTimeList)&&(dateTimeList.size()>0)) {
                result = new ArrayList<>();
                for(String str:dateTimeList) {
                    if(resultStock.getStorageTime().compareTo(DateUtil.parseDate(str).atStartOfDay()) < 0){
                        result.add(str);
                    }
                }
                dateTimeResult.setData(result);
            }
        }
        return dateTimeResult;
    }

    @Override
    public List<IovTrajectoryVo> getTrajectory(String vin, String startTime, String endTime) {
        CarDto carDto = carService.getCarByVin(vin);
        if(null == carDto) {
            return null;
        }
        if(null != startTime) {
            StockCarDto resultStock = stockCarService.getStorageTime(carDto.getId());
            if(null == resultStock) {
                return null;
            }
            if(DateUtil.parseDateTime(startTime).compareTo(resultStock.getStorageTime()) <0 ) {
                startTime = DateUtil.formatTime(resultStock.getStorageTime());
            }
        }
        ResponseResult<List<IovTrajectoryDto>> data = iovCarService.getTrajectory(vin, startTime, endTime);
        if((null != data)&&(ResponseCodeEnum.SUCCESS.getCode().equals(data.getCode()))) {
            return Convert.toIovTrajectoryVo(data.getData());
        }
        return null;
    }

    @Override
    public List<VehicleModlemakeVo> getVehicleMakeByVehicle() throws Exception {
        Map<String,Object> selectParams = new HashMap<>();
        //获取当前登录的经销商id
        Integer dealerId = RequestAttrUtil.getCurrentDealerId();
        List<Integer> storeIds = storeService.getAllStoreIdByDealer(dealerId);
        if((null != storeIds)&&(storeIds.size() > 0)) {
            List<Integer> stockIds = stockStoreService.getStockIds(storeIds);
            if((null != stockIds)&&(stockIds.size() > 0)) {
                selectParams.put("stockIds", stockIds);
            }else {
                selectParams.put("stockId", 0);
            }
        }else {
            selectParams.put("stockId", 0);
        }
        Paged<CarVo> paged = getCarList(selectParams, 1, Integer.MAX_VALUE);
        Set<Integer> vehicleIds = new HashSet<>();
        if((null != paged)&&(null != paged.getList())&&(0 != paged.getList().size())) {
            for(CarVo carVo : paged.getList()) {
                vehicleIds.add(carVo.getVehicleId());
            }
        }
        if((null != vehicleIds)&&(vehicleIds.size() > 0)) {
           return com.molichuxing.gateway.bff.basic.convertor.Convert.toVehicleModlemakeVo(vehicleBizService.getVehicleModlemakeBizDto(new ArrayList<>(vehicleIds)));
        }

        return null;
    }

    private Map<Integer, String> getVehicleName(List<CarDto> carDtoList) {
        Map<Integer, String> result = null;
        if(null != carDtoList && carDtoList.size() > 0) {
            List<Integer> ids = new ArrayList<>();
            for(CarDto carDto : carDtoList) {
                ids.add(carDto.getVehicleId());
            }
            result = vehicleBizService.getVehicleFullName(ids);
        }
        return result;
    }

    private void getVehicleStock(List<CarVo> carDtoList) throws Exception{
        if(null != carDtoList && carDtoList.size() > 0) {
            List<Integer> ids = new ArrayList<>();
            List<String> vins = new ArrayList<>();
            for (CarVo carDto : carDtoList) {
                ids.add(carDto.getId());
                vins.add(carDto.getVin());
            }
            Map<Integer, StockCarBizDto> stockCarBizMap = stockCarBizService.getStockBaseCars(ids);
            ResponseResult<Map<String, IovMileageDto>> iovMap = iovCarService.getMileageByVins(vins);
            Map<String, IovMileageDto> map = null;
            if((null != iovMap)&&(ResponseCodeEnum.SUCCESS.getCode().equals(iovMap.getCode()))) {
                map = new HashMap<>();
                map = iovMap.getData();
            }
            for (CarVo carDto : carDtoList) {
                //获取车辆网得里程
                if((null != map)&&(null != map.get(carDto.getVin()))) {
                    carDto.setDrivingName(map.get(carDto.getVin()).getOdo()+"");
                }
                if(null != stockCarBizMap) {
                    StockCarBizDto stockCarBizDto = stockCarBizMap.get(carDto.getId());

                    if(null != stockCarBizDto) {
                        if (stockCarBizDto.getStockType() == StockCarStockTypeEnum.ENTREPOT_STORAGE.getValue()) {
                            carDto.setStockName(stockCarBizDto.getStockName());
                        } else {
                            try{
                                DealerStoreInfoBizDto dealerStoreInfoBizDto = storeBizService.getDealerStoreInfo(stockCarBizDto.getStoreId());
                                carDto.setStockName(dealerStoreInfoBizDto.getDealerShortName() + "-" + dealerStoreInfoBizDto.getStoreShortName());
                            }catch(Exception e) {
                                logger.error("查询门店信息异常");
                            }
                        }
                    }
                }
            }
        }
    }

    private Map<Integer, VehicleColorDto> getVehicleColor(List<CarDto> carDtoList) {
        Map<Integer, VehicleColorDto> result = null;
        if(null != carDtoList && carDtoList.size() > 0) {
            List<Integer> ids = new ArrayList<>();
            for(CarDto carDto : carDtoList) {
                ids.add(carDto.getVehicleColorId());
            }
            result = vehicleColorService.getVehicleColors(ids);
        }
        return result;
    }

}
